package chaowan.inteceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object user = session.getAttribute("loginUser");

        // 登录用户放行
        if (user != null) {
            return true;
        }

        // 允许访问登录页、注册页、静态资源
        String uri = request.getRequestURI();
        if (uri.endsWith("/user/login.jsp")
                || uri.endsWith("/user/register.jsp")
                || uri.contains("/user/login")
                || uri.contains("/user/register")
                || uri.contains("/fonts/")
                || uri.endsWith("/favicon.ico")) {
            return true;
        }

        // 拦截未登录请求，重定向到 login.jsp
        response.sendRedirect(request.getContextPath() + "/user/login?notLogin=true");
        return false;
    }
}